package com.cskaoyan.day20;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class PasswordTest2 {

    public static void main(String[] args) throws InterruptedException {



        LogThread1 logThread = new LogThread1();
        logThread.setDaemon(true);
        logThread.start();

        Mythread1 mythread1 = new Mythread1();
        mythread1.start();


        TimeUnit.SECONDS.sleep(20);
    }
}

class Mythread1 extends Thread {
    volatile  static boolean flag = false;
    static StringBuffer sb = new StringBuffer();
    private static int password = (int) (Math.random() * 1000);

    static {
        System.out.println("密码生成成功：" + password);
    }

    @Override
    public void run() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < 1000; i++) {
            if (i == password) {
                String format = sdf.format(new Date());
                sb.append("[" + format + "]" + "尝试破解密码：" + i + ",   密码正确，破解成功！\n");
                flag = true;
                System.out.println("破解成功！开始写入日志文件...");
                return;
            }
            String format = sdf.format(new Date());
            sb.append("[" + format + "]" + "尝试破解密码：" + i + ",   密码错误，破解失败！\n");
        }
    }
}

class LogThread1 extends Thread {

    @Override
    public void run() {


        while (true) {

            // System.out.println(123);
            if (Mythread1.flag) {
                try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("Logpassword2.txt"))) {
                    // System.out.println(555);
                    out.write(Mythread1.sb.toString().getBytes());
                    System.out.println("日志已生成！");
                    break;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
